package biback.domain

import java.text.SimpleDateFormat

import eu.timepit.refined.api.Validate
import shapeless.Witness

import scala.util.Try

object refined {

  final case class ValidDate[S <: String](f: String)

  object ValidDate {
    private def isValidDate(s: String, f: String): Boolean = Try {
      assert(s.length == f.length)
      val sdf = new SimpleDateFormat(f)
      val d = sdf.parse(s)
      assert(s == sdf.format(d))
    }.isSuccess

    implicit def dateValidate[S <: String](implicit ws: Witness.Aux[S]): Validate.Plain[String, ValidDate[S]] =
      Validate.fromPredicate(
        p => isValidDate(p, ws.value),
        t => s""""[$t] invalid format [${ws.value}]"""",
        ValidDate(ws.value)
      )
  }

  final case class ValidCcy()

  object ValidCcy {
    private val all = List("CNY", "USD", "HKD", "EUR")
    implicit def ccyValidate: Validate.Plain[String, ValidCcy] =
      Validate.fromPredicate(p => all.contains(p), t => s"$t unsupported", ValidCcy())
  }

}
